#!/bin/bash



command_exists() {
  command -v "$@" > /dev/null 2>&1

}

print_title() {
  echo -e "\033[32m"
  echo -e "\n============================================="
  echo "$1"
  echo "============================================"
  echo -e "\033[0m"

}

cpu_usage() {
  print_title "CPU Usage"
  if command_exists top; then
	  top -bn1 | grep "Cpu(s)" | awk '{print  "User: " $2 "%, System: " $4 "%, Idle: " $6 "%, IOWait: " $5 "%"}'
  else
	  echo "Error: top command not found."
          exit 1
  fi


}

# 获取内存使用率和内存情况
memory_usage() {
    print_title "Memory Usage"
    if command_exists free; then
        free -m | awk 'NR==2{printf "Total: %sM, Used: %sM (%.2f%%), Free: %sM, Cache: %sM\n", $2, $3, $3*100/$2, $4, $6}'
    else
        echo "Error: free command not found."
        exit 1
    fi
}


# 获取磁盘分区及磁盘IO
disk_partitions() {
    print_title "Disk Partitions"
    if command_exists df; then
	    df -h
    else
	    echo "Error: df command not found."
	    exit 1
    fi
}



# 获取磁盘空间使用率
disk_io() {
    print_title "Disk IO"
    if command_exists iostat; then
        iostat -x 1 3
    else
        echo "Error: iostat command not found. Please install sysstat package."
        exit 1
    fi
}

# 获取网口带宽
network_bandwidth() {
    print_title "Network Bandwidth"
    if command_exists ifconfig; then
        ifconfig
    elif command_exists ip; then
        ip addr show
    else
        echo "Error: No network interface statistics tool found."
        exit 1
    fi
}

# 获取CPU和内存使用前五的进程
top_processes() {
    print_title "Top 5 CPU and Memory Processes"
    if command_exists ps; then
        ps aux --sort=-%cpu | head -5
        ps aux --sort=-%mem | head -5
    else
        echo "Error: ps command not found."
        exit 1
    fi
}

# 记录时间点
record_time() {
    echo -e "\033[34mTime of report: $(date '+%Y-%m-%d %H:%M:%S')\033[0m" # 蓝色高亮
}

# 主函数，调用所有性能监控函数
main() {
    record_time
    cpu_usage
    memory_usage
    disk_partitions
    disk_io
    network_bandwidth
    top_processes
}

# 调用主函数
main
